#pragma once
#include <iostream>
#include <algorithm>
#include <mutex>
#include <jsoncpp/json/json.h>
#include "../Common/httplib.h"
#include "oj_model2.hpp"
#include "oj_view.hpp"

namespace ns_control
{
    using namespace ns_model;
    using namespace ns_view;
    using namespace ns_util;
    using namespace ns_log;
    using namespace httplib;

    class Machine
    {
    public:
        Machine(std::string ip = "", int port = 0)
            : _ip(ip), _port(port), _load(0), _mtx(nullptr)
        {
            if (_ip != "" && _port != 0)
            {
                _mtx = new std::mutex();
            }
        }
        uint64_t Load()
        {
            uint64_t load = 0;
            if (_mtx)
            {
                _mtx->lock();
                load = _load;
                _mtx->unlock();
            }
            return load;
        }
        void IncLoad()
        {
            if (_mtx)
            {
                _mtx->lock();
                ++_load;
                _mtx->unlock();
            }
        }
        void DecLoad()
        {
            if (_mtx)
            {
                _mtx->lock();
                --_load;
                _mtx->unlock();
            }
        }
        void ClearLoad()
        {
            if (_mtx)
            {
                _mtx->lock();
                _load = 0;
                _mtx->unlock();
            }
        }

    public:
        std::string _ip;
        int _port;

    private:
        uint64_t _load;
        std::mutex *_mtx; // mutex锁不能拷贝，所以后续要使用Machine结构体用指针来管理
    };
    const std::string confPath = "./conf/service_machines.conf";
    class LoadBlance
    {
    private:
        std::vector<Machine> _machines; // 主机列表
        std::vector<int> _online;       // 在线主机列表，存的是下标即编号
        std::vector<int> _offline;      // 离线主机列表
        std::mutex _mtx;                // 负载均衡锁
    public:
        LoadBlance()
        {
            assert(LoadConf(confPath));
            LOG(INFO) << "编译服务主机配置成功!" << "\n";
        }
        ~LoadBlance()
        {
        }
        bool LoadConf(const std::string conf_path)
        {
            std::ifstream in(conf_path);
            if (!in.is_open())
            {
                LOG(FATAL) << "加载主机配置文件失败,请检查相关配置!" << "\n";
                return false;
            }
            std::string line;
            while (getline(in, line))
            {
                std::vector<std::string> tokens;
                StringUtil::SplitString(line, &tokens, ":");
                if (tokens.size() != 2)
                {
                    LOG(WARNING) << "当前配置文件出错:" << line << "\n";
                    continue;
                }
                Machine m(tokens[0], stoi(tokens[1]));
                _online.push_back(_machines.size()); // 下标从0开始记录
                _machines.push_back(m);              // 主机入列表
            }
            in.close();
            return true;
        }
        // 负载均衡选择上线服务主机，轮询最小连接数。均为输出型参数，mutex不能拷贝,故Machine不能拷贝使用二级指针管理
        bool SmartChoice(int *id, Machine **m)
        {
            _mtx.lock();
            if (_online.size() == 0)
            {
                _mtx.unlock();
                LOG(FATAL) << "此时编译服务没有主机上线，请检查配置!" << "\n";
                return false;
            }
            *id = _online[0];
            *m = &_machines[_online[0]];
            uint64_t min_load = _machines[_online[0]].Load();
            for (int i = 1; i < _online.size(); i++)
            {
                uint64_t cur_load = _machines[_online[i]].Load();
                if (min_load > cur_load)
                {
                    min_load = cur_load;
                    *m = &_machines[_online[i]];
                    *id = _online[i];
                }
            }
            _mtx.unlock();
            return true;
        }
        //请求失败将上线服务主机移除
        void OfflineMachine(int &id)
        {
            _mtx.lock();
            for (auto iter = _online.begin(); iter != _online.end(); iter++)
            {
                if (*iter == id)
                {
                    _online.erase(iter);//迭代器失效
                    _offline.push_back(id);
                    _machines[id].ClearLoad();
                    break;
                }
            }
            _mtx.unlock();
        }
        //上线功能
        void OnlineMachine()
        {
            _mtx.lock();
            _online.insert(_online.end(),_offline.begin(),_offline.end());//将离线主机（迭代器范围）插入到在线主机end迭代器处
            _offline.erase(_offline.begin(),_offline.end());//情况离线主机容器
            _mtx.unlock();
            LOG(INFO)<<"所有主机已上线"<<"\n";
        }
    };

    class Control
    {
    private:
        Model _model;
        View _view;
        LoadBlance _load_blance;

    public:
        Control()
        {
        }
        ~Control()
        {
        }
        void RecoveryMachine()
        {
            _load_blance.OnlineMachine();
        }
        // 构造题目列表网页
        bool AllQuestions(std::string *html)
        {
            std::vector<Question> all;
            if (!_model.GetAllQestions(&all))
            {
                *html = "获取题库失败,无法构建网页";
                return false;
            }
            sort(all.begin(), all.end(), [](const Question &q1, const Question &q2)
                 { return q1._number < q2._number; });
            _view.AllExpandHtml(all, html);
            return true;
        }
        // 构造指定题目网页
        bool OneQuestion(const std::string &number, std::string *html)
        {
            Question q;
            if (!_model.GetOneQuestion(number, &q))
            {
                *html = "获取题目信息失败,无法构建网页";
                return false;
            }
            _view.OneExpandHtml(q, html);
            return true;
        }
        // 输入题目编号，in_json用户提交的json串包含(code、input),out_json为输出提交串
        void Judge(const std::string &id,const std::string &in_json, std::string *out_json)
        {
            // 1.根据编号获取题目
            Question q;
            if (!_model.GetOneQuestion(id, &q))
                return;
            // 2.反序列化用户提交串
            Json::Value in_value;
            Json::Reader read;
            read.parse(in_json, in_value);
            // 3.拼接用户提交代码和内置测试代码为新json
            Json::FastWriter writer;
            Json::Value compiler_value;
            compiler_value["code"] = in_value["code"].asString() + "\n" + q._tail;
            compiler_value["input"] = in_value["input"].asString();
            compiler_value["cpu_limit"] = q._cpu_limit;
            compiler_value["mem_limit"] = q._mem_limit;
            std::string compiler_json = writer.write(compiler_value);
            // 4.负载均衡选择编译主机服务
            while (true)
            {
                int machine_id = 0;
                Machine *m = nullptr;
                if (!_load_blance.SmartChoice(&machine_id, &m))
                {
                    break;
                }
                // 5.客户端发起http请求
                Client cli(m->_ip, m->_port);
                m->IncLoad();
                LOG(INFO) << "主机编号:" << machine_id << "详细信息ip:" << m->_ip << " port:" << m->_port << "当前负载:" << m->Load() << "\n";
                // 发起post请求与编译服务相同路径
                if (auto res = cli.Post("/compile_and_run", compiler_json, "application/json;charset=utf-8"))
                {
                    // 发送成功，返回结果串在body中
                    if (res->status == 200)
                    {
                        *out_json = res->body;
                        m->DecLoad();
                        break;
                    }
                    m->DecLoad();
                }
                else
                {
                    // 请求失败
                    LOG(ERROR) << "主机编号:" << machine_id << "详细信息ip:" << m->_ip << " port:" << m->_port << "可能已经离线....." << "\n";
                    _load_blance.OfflineMachine(machine_id); // 下线主机,负载清0
                }
            }
        }
    };
}